#!/bin/sh
#
# validate session-id
mystat() {
   stat -c "%a" "$1" 2>/dev/null && return 0
   statline=`stat -s "$1"` || { echo "Cannot stat"; exit 1; }
   echo "$statline" | sed -e "s/.*st_mode=//;s/ .*//"
}

SESSION_ID=`echo "$1" | egrep "^[-0123456789abcdef]*$"`
if [ -z "$SESSION_ID" ]; then
  echo "Invalid sessionid"
  exit 1
fi

TO_UID=`echo "$2" | grep "^[0123456789]*$"`
if [ -z "$TO_UID" ]; then
  echo "No userid specifified"
  exit 1
fi

TO_GID=`echo "$3" | grep "^[0123456789]*$"`
if [ -z "$TO_GID" ]; then
  echo "No groupid specifified"
  exit 1
fi

TO_DIR="$4"
if [ -z "$TO_DIR" ]; then
  echo "Invalid directory specified"
  exit 1
fi

echo "$TO_DIR" | egrep "^/var/open" >/dev/null && {
  echo "Invalid directory specified"
  exit 1
}

if [ ! -d "$TO_DIR" ]; then
  exit 0
fi

# create the rollback directory for this session if it didn't exist
if [ ! -d /var/opencore/conf/rollback/$SESSION_ID ]; then
  mkdir /var/opencore/conf/rollback/$SESSION_ID || {
    echo "Error creating rollback directory"
    exit 1
  }
fi

# generate the filename for the rollback-file
RBFN=`echo "$TO_DIR" | tr "./ " ___ | sed -e "s/^_//"`
RBFILE="/var/opencore/conf/rollback/$SESSION_ID/${RBFN}.rollback"

ST=`mystat "$TO_DIR"`
if [ -z "$ST" ]; then
  echo "Error reading stat result"
  exit 1
fi

# create the rollback file (including tar archive of the directory contents)
echo "RMUSERDIR $TO_UID $TO_GID $ST $TO_DIR" > $RBFILE
opwd=`pwd`
if cd "$TO_DIR" 2>/dev/null; then
  /var/opencore/tools/runas $TO_UID $TO_GID /bin/tar pcf - . | bzip2 -c >> $RBFILE
  # with the contents safely tucked away we can now nuke it from orbit
  cd "$opwd"
  /var/opencore/tools/runas $TO_UID $TO_GID /bin/rm -rf "$TO_DIR"
else
  echo "Error changing to directory for rollback"
  fi
endif

